#include "patientdetailwidget.h"
#include "ui_patientdetailwidget.h"
#include "../../network/networkclient.h"
#include "medicalrecorddetailwidget.h"
#include <QMessageBox>
#include <QJsonArray>
#include <QDate>

PatientDetailWidget::PatientDetailWidget(const Doctor& doctor, int patientId, int appointmentId, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PatientDetailWidget),
    m_doctor(doctor),
    m_patientId(patientId),
    m_appointmentId(appointmentId),
    m_hasCreatedRecord(false),
    m_hasCreatedPrescription(false) {
    ui->setupUi(this);
    
    // 设置历史病历表格
    ui->medicalRecordTable->setColumnCount(5);
    ui->medicalRecordTable->setHorizontalHeaderLabels(
        {"病历ID", "就诊时间", "诊断", "治疗方案", "医生"});
    ui->medicalRecordTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->medicalRecordTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    // 设置列宽
    ui->medicalRecordTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->medicalRecordTable->setColumnWidth(0, 80);
    ui->medicalRecordTable->setColumnWidth(1, 150);
    ui->medicalRecordTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); // 诊断自动拉伸
    ui->medicalRecordTable->setColumnWidth(3, 200);
    ui->medicalRecordTable->setColumnWidth(4, 100);
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PatientDetailWidget::onMessageReceived);
    
    // 加载数据
    loadPatientInfo();
    loadAppointmentInfo();
    loadMedicalRecords();
    
    // 检查本次预约是否已完成病历和处方
    checkAppointmentCompletion();
}

PatientDetailWidget::~PatientDetailWidget() {
    delete ui;
}

void PatientDetailWidget::loadPatientInfo() {
    QJsonObject request;
    request["patient_id"] = m_patientId;
    NetworkClient::instance().sendRequest(MSG_GET_PATIENT_INFO, request);
}

void PatientDetailWidget::loadAppointmentInfo() {
    // 通过预约ID获取预约详情
    QJsonObject request;
    request["appointment_id"] = m_appointmentId;
    NetworkClient::instance().sendRequest(MSG_GET_APPOINTMENT_DETAIL, request);
}

void PatientDetailWidget::loadMedicalRecords() {
    QJsonObject request;
    request["patient_id"] = m_patientId;
    NetworkClient::instance().sendRequest(MSG_GET_MEDICAL_RECORDS, request);
}

void PatientDetailWidget::checkAppointmentCompletion() {
    if (m_appointmentId <= 0) {
        return;  // 无效的预约ID
    }
    
    QJsonObject request;
    request["appointment_id"] = m_appointmentId;
    NetworkClient::instance().sendRequest(MSG_CHECK_APPOINTMENT_COMPLETION, request);
}

void PatientDetailWidget::on_backButton_clicked() {
    emit backToAppointments();
}

void PatientDetailWidget::on_createRecordButton_clicked() {
    if (m_patient.id == 0) {
        QMessageBox::warning(this, "提示", "患者信息未加载，请稍后再试");
        return;
    }
    
    // 获取预约时间
    QDateTime appointmentTime;
    qDebug() << "预约信息:" << m_appointmentInfo;
    if (m_appointmentInfo.contains("appointment_time")) {
        QString timeStr = m_appointmentInfo["appointment_time"].toString();
        qDebug() << "预约时间字符串:" << timeStr;
        
        // 尝试多种时间格式
        appointmentTime = QDateTime::fromString(timeStr, "yyyy-MM-dd HH:mm:ss");
        if (!appointmentTime.isValid()) {
            appointmentTime = QDateTime::fromString(timeStr, Qt::ISODate);  // ISO 格式
        }
        if (!appointmentTime.isValid()) {
            appointmentTime = QDateTime::fromString(timeStr, "yyyy-MM-ddTHH:mm:ss.zzz");  // 带毫秒
        }
        
        qDebug() << "解析后的预约时间:" << appointmentTime << "是否有效:" << appointmentTime.isValid();
    } else {
        qDebug() << "预约信息中没有 appointment_time 字段";
    }
    
    emit showCreateRecord(m_doctor, m_patient, m_appointmentId, appointmentTime);
}

void PatientDetailWidget::on_createPrescriptionButton_clicked() {
    if (m_patient.id == 0) {
        QMessageBox::warning(this, "提示", "患者信息未加载，请稍后再试");
        return;
    }
    
    // 检查是否已创建病历（强制顺序：先病历后处方）
    if (!m_hasCreatedRecord) {
        QMessageBox::warning(this, "提示", "请先创建病历，然后再开具处方！");
        return;
    }
    
    // 获取最新病历ID（历史病历记录第一条）
    int latestRecordId = 0;
    if (m_medicalRecords.size() > 0) {
        QJsonObject latestRecord = m_medicalRecords[0].toObject();
        latestRecordId = latestRecord["id"].toInt();
    }
    
    emit showCreatePrescription(m_doctor, m_patient, m_appointmentId, latestRecordId);
}

void PatientDetailWidget::on_medicalRecordTable_cellDoubleClicked(int row, int column) {
    Q_UNUSED(column);
    
    // 检查是否有病历数据
    if (row < 0 || row >= m_medicalRecords.size()) {
        return;
    }
    
    // 获取病历数据
    QJsonObject recordJson = m_medicalRecords[row].toObject();
    MedicalRecord record = MedicalRecord::fromJson(recordJson);
    
    // 打开病历详情窗口
    MedicalRecordDetailWidget *detailWidget = new MedicalRecordDetailWidget(record);
    detailWidget->setAttribute(Qt::WA_DeleteOnClose);
    detailWidget->setWindowModality(Qt::ApplicationModal);
    detailWidget->resize(700, 600);
    detailWidget->show();
}

void PatientDetailWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_PATIENT_INFO_RESPONSE) {
        if (data["success"].toBool()) {
            Patient patient = Patient::fromJson(data);
            m_patient = patient;
            updatePatientInfo(patient);
        }
    } else if (type == MSG_GET_APPOINTMENT_DETAIL_RESPONSE) {
        if (data["success"].toBool()) {
            m_appointmentInfo = data["appointment"].toObject();
            updateAppointmentInfo(m_appointmentInfo);
        }
    } else if (type == MSG_GET_MEDICAL_RECORDS_RESPONSE) {
        if (data["success"].toBool()) {
            m_medicalRecords = data["records"].toArray();  // 保存病历数据
            updateMedicalRecordsTable(m_medicalRecords);
        }
    } else if (type == MSG_CHECK_APPOINTMENT_COMPLETION_RESPONSE) {
        if (data["success"].toBool()) {
            m_hasCreatedRecord = data["has_record"].toBool();
            m_hasCreatedPrescription = data["has_prescription"].toBool();
            
            // 更新按钮状态或提示
            if (m_hasCreatedRecord && m_hasCreatedPrescription) {
                qDebug() << "本次预约已完成病历和处方";
            } else if (m_hasCreatedRecord) {
                qDebug() << "本次预约已创建病历，等待开具处方";
            }
        }
    }
}

void PatientDetailWidget::updatePatientInfo(const Patient& patient) {
    ui->patientNameLabel->setText(patient.realName);
    ui->patientIdLabel->setText(QString::number(patient.id));
    ui->genderLabel->setText(patient.gender);
    ui->ageLabel->setText(QString("%1岁").arg(QDate::currentDate().year() - patient.birthDate.year()));
    ui->phoneLabel->setText(patient.phone);
    ui->addressLabel->setText(patient.address.isEmpty() ? "未填写" : patient.address);
    ui->allergiesLabel->setText(patient.allergies.isEmpty() ? "无" : patient.allergies);
    ui->medicalHistoryText->setPlainText(patient.medicalHistory.isEmpty() ? "无" : patient.medicalHistory);
}

void PatientDetailWidget::updateAppointmentInfo(const QJsonObject& appointment) {
    // 格式化预约时间为"日期 时间段"格式
    QString appointmentTimeStr = appointment["appointment_time"].toString();
    QDateTime appointmentTime = QDateTime::fromString(appointmentTimeStr, "yyyy-MM-dd HH:mm:ss");
    if (!appointmentTime.isValid()) {
        appointmentTime = QDateTime::fromString(appointmentTimeStr, Qt::ISODate);
    }
    QString formattedTime;
    if (appointmentTime.isValid()) {
        QString dateStr = appointmentTime.toString("yyyy-MM-dd");
        int hour = appointmentTime.time().hour();
        QString timeSlot = QString("%1:00-%2:00")
            .arg(hour, 2, 10, QChar('0'))
            .arg(hour + 1, 2, 10, QChar('0'));
        formattedTime = QString("%1 %2").arg(dateStr, timeSlot);
    } else {
        formattedTime = appointmentTimeStr;
    }
    
    ui->appointmentTimeLabel->setText(formattedTime);
    ui->appointmentStatusLabel->setText(appointment["status"].toString());
    ui->symptomsText->setPlainText(appointment["symptoms"].toString());
}

void PatientDetailWidget::updateMedicalRecordsTable(const QJsonArray& records) {
    ui->medicalRecordTable->setRowCount(0);
    
    for (const QJsonValue& value : records) {
        QJsonObject record = value.toObject();
        
        int row = ui->medicalRecordTable->rowCount();
        ui->medicalRecordTable->insertRow(row);
        
        ui->medicalRecordTable->setItem(row, 0,
            new QTableWidgetItem(QString::number(record["id"].toInt())));
        ui->medicalRecordTable->setItem(row, 1,
            new QTableWidgetItem(record["visit_time"].toString()));
        ui->medicalRecordTable->setItem(row, 2,
            new QTableWidgetItem(record["diagnosis"].toString()));
        ui->medicalRecordTable->setItem(row, 3,
            new QTableWidgetItem(record["treatment"].toString()));
        ui->medicalRecordTable->setItem(row, 4,
            new QTableWidgetItem(record["doctor_name"].toString()));
    }
    
    ui->recordCountLabel->setText(QString("共 %1 条病历记录").arg(records.size()));
}

